package com.baway.login.view

import android.animation.Animator
import android.animation.AnimatorListenerAdapter
import android.animation.ValueAnimator
import android.view.View
import android.view.animation.LinearInterpolator
import androidx.activity.viewModels
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.baway.base.path.RouterPath
import com.baway.common.event.CustomEvent
import com.baway.common.util.DialogUtils
import com.baway.common.view.BaseMvvmActivity
import com.baway.login.R
import com.baway.login.databinding.ActivityLoginBinding
import com.baway.login.vm.LoginViewModel
import com.blankj.utilcode.util.RegexUtils
import com.blankj.utilcode.util.ToastUtils
import dagger.hilt.android.AndroidEntryPoint
import org.greenrobot.eventbus.EventBus
import kotlin.random.Random

@Route(path = RouterPath.PATH_LOGIN_PAGE)
@AndroidEntryPoint
class LoginActivity : BaseMvvmActivity<ActivityLoginBinding>() {

    private val mViewModel: LoginViewModel by viewModels()

    private var mValueAnimator: ValueAnimator? = null

    private var mCountValue = 0


    override fun getLayoutId(): Int = R.layout.activity_login

    override fun initViews() {
        //登录面板
        mDataBinding.includeLoginLayout.run {
            //登录
            tvLoginBtn.setOnClickListener {
                loginToServer()
            }

            //注册
            tvRegisterNew.setOnClickListener {
                mDataBinding.cltLogin.visibility = View.GONE
                mDataBinding.cltRegister.visibility = View.VISIBLE
            }

            //忘记密码
            tvPwdForget.setOnClickListener {
                ToastUtils.showLong("忘记密码！！")
            }
        }

        //注册面板
        mDataBinding.includeRegisterLayout.run {
            //验证码
            tvVerifyCode.setOnClickListener {
                getPhoneVerifyCode()
            }

            //注册
            tvRegisterBtn.setOnClickListener {
                    registerToServer()
            }

            //已有账号
            tvGotoLogin.setOnClickListener {
                mDataBinding.cltLogin.visibility = View.VISIBLE
                mDataBinding.cltRegister.visibility = View.GONE
            }

        }

    }

    /**
     * Android中三种动画：帧动画，补间动画和属性动画
     * 帧动画：使用xml定义一组图片，性能差，对内存消耗较大（不推荐）
     * 补间动画：指定关键帧，其他路径上动画帧交给系统提供差值器，不会改变组件原来属性（位置，大小，颜色等）
     * 属性动画：使用ObjectAnimator和ValueAnimator, 前者作用在View对象，后者作用于摸某一个值的变化
     */
    private fun getPhoneVerifyCode(){
        //创建属性动画
        mValueAnimator = ValueAnimator.ofInt(15, 0).apply {
            duration = 15000
            interpolator = LinearInterpolator() //线性匀速差值器

            //监听动画值变化
            addUpdateListener {
                var count = it.animatedValue as Int //可能产生一样数字
                if (count != mCountValue){
                    mCountValue = count
                    mDataBinding.includeRegisterLayout.tvVerifyCode.text = "${mCountValue}秒重新获取"
                }

            }

            //动画状态监听
            addListener(object : AnimatorListenerAdapter(){
                override fun onAnimationEnd(animation: Animator) {
                    //使用随机数生成6位数验证码
                    val verifyCode = Random.nextDouble(100000.00, 1000000.00).toInt()
                    mDataBinding.includeRegisterLayout.edtVerifyCode.setText("$verifyCode")
                    mDataBinding.includeRegisterLayout.tvVerifyCode.text = "获取验证码"

                }
            })
        }

        //启动动画
        mValueAnimator?.start()
    }

    override fun onDestroy() {
        super.onDestroy()
        //取消动画并标识为可回收对象
        mValueAnimator?.cancel()
        mValueAnimator = null
    }

    private fun registerToServer(){
        DialogUtils.showLoading(this@LoginActivity, "注册中...")

        val userName = mDataBinding.includeRegisterLayout.edtPhoneNum.text.toString().trim()
        val password = mDataBinding.includeRegisterLayout.edtPwd.text.toString().trim()
        val repassword = mDataBinding.includeRegisterLayout.edtRePwd.text.toString().trim()

        //手机号检验
        if (!RegexUtils.isMobileSimple(userName)){
            ToastUtils.showLong("请输入正确的手机号！！")
            return
        }

        //检验两次输入的密码是否一致
        if (password != repassword){
            ToastUtils.showLong("您输入的密码不一致！！")
            return
        }

        //执行注册
        mViewModel.registerToServer(userName, password)
    }

    private fun loginToServer(){
        DialogUtils.showLoading(this@LoginActivity, "登录中...")

        val userName = mDataBinding.includeLoginLayout.edtUserName.text.toString().trim()
        val password = mDataBinding.includeLoginLayout.edtPassWold.text.toString().trim()
        //发起登录
        if (!userName.isNullOrEmpty() && !password.isNullOrEmpty()){
            mViewModel.loginToServer(userName, password)
        } else {
            ToastUtils.showLong("账号和密码不能为空！！")
        }
    }


    override fun observeDataChanged() {
        mViewModel.mError.observe(this@LoginActivity){
            //关闭Loading
            DialogUtils.dimissLoading()

            ToastUtils.showLong(it)
        }

        //登录和注册成功订阅
        mViewModel.mSuccess.observe(this@LoginActivity){
            //关闭Loading
            DialogUtils.dimissLoading()

            //注册成功业务
            if (it.typeId == 0){
                ToastUtils.showLong("账号注册成功！！")

                //清理输入框
                mDataBinding.includeRegisterLayout.run {
                    edtPhoneNum.setText("")
                    edtVerifyCode.setText("")
                    edtPwd.setText("")
                    edtRePwd.setText("")
                }

                //切换到登录面板
                mDataBinding.cltRegister.visibility = View.GONE
                mDataBinding.cltLogin.visibility = View.VISIBLE

                //回显新账号和密码
                mDataBinding.includeLoginLayout.edtUserName.setText(it.username)
                mDataBinding.includeLoginLayout.edtPassWold.setText(it.password)

            }

            //登录成功
            if (it.typeId == 1){
                ToastUtils.showLong("账号登录成功！！")
                //跳转到主页面
                ARouter.getInstance().build(RouterPath.PATH_MAIN_PAGE).navigation()

                //给首页发送事件
                EventBus.getDefault().post(CustomEvent(target = "HomeFragment", data = it.id, type = 100))

                //关闭登录页面
                this@LoginActivity.finish()
            }

        }

    }






}